package com.doubao.doubao_admin.jwt;

import com.doubao.doubao_admin.utils.JwtUtils;
//import org.apache.shiro.util.AntPathMatcher;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JwtAuthenticationFiler extends OncePerRequestFilter {

    private static final PathMatcher pathMatcher = (PathMatcher) new AntPathMatcher();
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        System.out.println("reuest过滤前：" + request.getHeader("Authorization"));
        try {

            if (isProtectedUrl(request)){
                if (!request.getMethod().equals("OPTIONS")){
                    request = JwtUtils.validateTokenAndAddUserIdToHeader(request);
                }
            }
        }catch (Exception e){

            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,e.getMessage());
        }

        System.out.println("Request after being filtered: " + request.getHeader("userName"));
        filterChain.doFilter(request, response);
    }

    private boolean isProtectedUrl(HttpServletRequest request){

        List<String> protectedPaths = new ArrayList<>();
        protectedPaths.add("/ums/user/info");
        protectedPaths.add("/post/create");
        protectedPaths.add("/post/update");
        protectedPaths.add("/post/delete/*");
        protectedPaths.add("/comment/add_comment");
        protectedPaths.add("/relationship/subscribe/*");
        protectedPaths.add("/relationship/unsubscribe/*");
        protectedPaths.add("/relationship/validate/*");
        boolean bFind = false;
        for (String passedPath : protectedPaths){
            bFind = pathMatcher.match(passedPath,request.getServletPath());

            if (bFind){
                break;
            }
        }
        return bFind;

    }
}
